package com.alex.wechat.app.handler;

import java.util.Date;
import java.util.Map;

import org.jeecgframework.web.cgform.common.CgAutoListConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alex.wechat.app.config.WxAppContext;
import com.alex.wechat.core.handler.WxAccountType;
import com.alex.wechat.core.handler.WxHandler;
import com.alex.wechat.mp.message.receive.entity.WxReceiveText;
import com.alex.wechat.mp.message.receive.service.WxReceiveTextServiceI;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.message.bean.WxXmlMessage;
import me.chanjar.weixin.message.rule.WxMessageHandler;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

/**
 * 处理小程序的客服消息
 * 
 * @author Debenson
 * @since 0.1
 */
@WxHandler(priority = Integer.MIN_VALUE, accountType = WxAccountType.APP)
public class DefaultAppMsgHandler implements WxMessageHandler {
  private static final Logger logger = LoggerFactory.getLogger(DefaultAppMsgHandler.class);

  @Autowired
  private WxReceiveTextServiceI receiveTextService;

  @Override
  public String handle(WxXmlMessage wxMessage, Map<String, Object> context)
      throws WxErrorException {
    try {
      saveReceiveText(wxMessage);
    } catch (Exception e) {
      logger.error("", e);
    }

    WxMpXmlOutMessage m = WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
        .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
    return m.toXml();
  }

  /**
   * 保存接收到的信息
   *
   * @param msg
   * @return
   */
  private WxReceiveText saveReceiveText(WxXmlMessage msg) {
    WxReceiveText recvMsg = new WxReceiveText();
    recvMsg.setContent(msg.getContent());
    recvMsg.setCreateDate(new Date());
    recvMsg.setUpdateDate(new Date());
    recvMsg.setFromUserName(msg.getFromUser());
    recvMsg.setToUserName(msg.getToUser());
    recvMsg.setMsgId(String.valueOf(msg.getMsgId()));
    recvMsg.setMsgType(msg.getMsgType());
    recvMsg.setResponse(CgAutoListConstant.BOOL_FALSE);
    recvMsg.setAccountId(WxAppContext.getOriginalId());
    recvMsg.setEvent(msg.getEvent());
    recvMsg.setEventKey(msg.getEventKey());
    recvMsg.setPictureUrl(msg.getPicUrl());
    recvMsg.setMediaId(msg.getMediaId());
    recvMsg.setThumbMediaId(msg.getThumbMediaId());
    recvMsg.setFormat(msg.getFormat());
    recvMsg.setRecognition(msg.getRecognition());
    recvMsg.setLocationX(msg.getLocationX() == null ? null : msg.getLocationX().toString());
    recvMsg.setLocationY(msg.getLocationY() == null ? null : msg.getLocationY().toString());
    recvMsg.setLocationLabel(msg.getLabel());
    receiveTextService.save(recvMsg);
    return recvMsg;
  }

}
